/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.grouporder.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.api.service.ApiService;
import com.jeeplus.modules.grouporder.entity.GroupOrder;
import com.jeeplus.modules.grouporder.mapper.GroupOrderMapper;
import com.jeeplus.modules.grouporder.entity.OrderGift;
import com.jeeplus.modules.grouporder.mapper.OrderGiftMapper;
import com.jeeplus.modules.grouprefund.entity.GroupRefund;
import com.jeeplus.modules.grouprefund.mapper.GroupRefundMapper;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.msg.service.MsgService;
import com.jeeplus.modules.msgexample.entity.MsgExample;
import com.jeeplus.modules.msgexample.service.MsgExampleService;
import com.jeeplus.modules.productgroup.entity.ProductGroup;
import com.jeeplus.modules.productgroup.mapper.ProductGroupMapper;
import com.jeeplus.modules.store.service.StoreService;

/**
 * 拼团订单Service
 * @author lixinapp
 * @version 2019-10-26
 */
@Service
@Transactional(readOnly = true)
public class GroupOrderService extends CrudService<GroupOrderMapper, GroupOrder> {

	@Autowired
	private OrderGiftMapper orderGiftMapper;
	@Autowired
	private ProductGroupMapper productGroupMapper;
	@Autowired
	private GroupRefundMapper groupRefundMapper;
	@Autowired
	private ApiService apiService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private MsgExampleService msgExampleService;
	@Autowired
	private MsgService msgService;
	
	public GroupOrder get(String id) {
		GroupOrder groupOrder = super.get(id);
		if (groupOrder != null) {
			groupOrder.setOrderGiftList(orderGiftMapper.findList(new OrderGift(groupOrder)));
		}
		return groupOrder;
	}
	
	public List<GroupOrder> findList(GroupOrder groupOrder) {
		return super.findList(groupOrder);
	}
	
	public Page<GroupOrder> findPage(Page<GroupOrder> page, GroupOrder groupOrder) {
		return super.findPage(page, groupOrder);
	}
	
	@Transactional(readOnly = false)
	public void save(GroupOrder groupOrder) {
		super.save(groupOrder);
		for (OrderGift orderGift : groupOrder.getOrderGiftList()){
			if (orderGift.getId() == null){
				continue;
			}
			if (OrderGift.DEL_FLAG_NORMAL.equals(orderGift.getDelFlag())){
				if (StringUtils.isBlank(orderGift.getId())){
					orderGift.setOrder(groupOrder);
					orderGift.preInsert();
					orderGiftMapper.insert(orderGift);
				}else{
					orderGift.preUpdate();
					orderGiftMapper.update(orderGift);
				}
			}else{
				orderGiftMapper.delete(orderGift);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(GroupOrder groupOrder) {
		super.delete(groupOrder);
		orderGiftMapper.delete(new OrderGift(groupOrder));
	}

	/**
	 * 生成订单
	 * @param groupOrder 订单
	 * @param province 代理省份
	 * @param city 代理城市
	 * @param area 代理区县
	 */
	@Transactional(readOnly = false)
	public void insert(GroupOrder groupOrder, String province, String city, String area) {
		save(groupOrder);
		// 减库存
		mapper.execUpdateSql("UPDATE t_product_sku SET stock = stock - "+groupOrder.getQty()+" WHERE id = '"+groupOrder.getSkuId()+"'");
		// 加销量
		mapper.execUpdateSql("UPDATE t_product SET sales = sales + "+groupOrder.getQty()+" WHERE id = '"+groupOrder.getProduct().getId()+"'");

	}

	/**
	 * 支付后处理
	 * @param groupOrder
	 */
	@Transactional(readOnly = false)
	public void pay(GroupOrder groupOrder) {
		super.save(groupOrder);

		// 处理拼团状态
		ProductGroup group = productGroupMapper.get(groupOrder.getGroupId());
		if (group != null && "0".equals(group.getState())) {
			group.setState("1");
			group.setEndDate(new Date());
			productGroupMapper.update(group);
		}
		//判断是否是拼购订单
		if (groupOrder.getPgOrder().equals("0")) {
			// 调用三方
			Member member = memberService.get(groupOrder.getMember());
			if (member != null) {
				JSONObject object = apiService.orderPay(String.valueOf(groupOrder.getQty()), groupOrder.getId(), member.getId(), groupOrder.getProvince(), groupOrder.getCity(), groupOrder.getMarea(), groupOrder.getStore().getStoreCode(), groupOrder.getAmount(), groupOrder.getPoint(), "0", DateUtils.getDateTime(), DateUtils.getDateTime(), "YD",  groupOrder.getProduct().getId(), "PTZQ", groupOrder.getPt_fwmoney(), groupOrder.getDlbt(),groupOrder.getProductTitle(),"0", groupOrder.getAmount(),"0","0");
				if (!"0000".equals(object.getString("respCode"))) {
					logger.error("我惠会员系统订单支付失败：" + object.getString("respMsg"));
				}
			}

			// 发消息
			MsgExample example = msgExampleService.getByType("9");
			if (example != null) {
				msgService.insert(groupOrder.getMember(), "系统消息", example.getContent());
			}
		} else {
			// 发消息
			MsgExample example = msgExampleService.getByType("13");
			if (example != null) {
				msgService.insert(groupOrder.getMember(), "系统消息", example.getContent());
			}
		}

		
		// 处理代理申请
		/*if ("1".equals(groupOrder.getProxyType())) {
			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("POrderNO", groupOrder.getId()));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.MSMSurePay, entityList);
			if ("0000".equals(jsonObject.getString("respCode"))) {
				// 处理本地代理结果
				ProxyOrder proxyOrder = new ProxyOrder();
				proxyOrder.setOrderId(groupOrder.getId());
				List<ProxyOrder> orderList = proxyOrderService.findList(proxyOrder);
				if (!orderList.isEmpty()) {
					for (ProxyOrder order : orderList) {
						order.setState("1");
						order.setPayDate(new Date());
						order.setPayType(groupOrder.getPayType());
						order.setOrderNo(groupOrder.getPayNo());
						proxyOrderService.save(order);
					}
				}
			}
		}*/
	}

	/**
	 * 退款处理
	 * @param groupOrder
	 * @param type 1同意 2拒绝
	 */
	@Transactional(readOnly = false)
	public void refund(GroupOrder groupOrder, String type) {
		// 查询退款申请列表
		GroupRefund groupRefund = new GroupRefund();
		groupRefund.setOrderId(groupOrder.getId());
		groupRefund.setState("0");
		List<GroupRefund> list = groupRefundMapper.findList(groupRefund);
		for (GroupRefund refund : list) {
			if ("1".equals(type)) {// 同意
				refund.setState("1");
			} else {// 拒绝
				refund.setState("2");
			}
			refund.setAuditDate(new Date());
			groupRefundMapper.update(refund);
		}
		
		// 修改订单状态
		String amount = "0";
		if ("1".equals(type)) {// 同意
			groupOrder.setState("7");
			groupOrder.setRefundDate(new Date());
			amount = list.get(0).getAmount();
		} else {// 拒绝
			groupOrder.setState(list.get(0).getOrderState());
		}
		mapper.update(groupOrder);
		
		// 退款
		if ("1".equals(type)) {// 同意
			// 退款给用户
			apiService.refund(groupOrder.getPayNo(), amount, groupOrder.getAmount(), groupOrder.getPayType(),groupOrder.getTrade_type());
			// 给商家结算
			BigDecimal money = new BigDecimal(groupOrder.getMoney()).subtract(new BigDecimal(amount));// 结算价
			if (money.compareTo(BigDecimal.ZERO) < 0) {
				money = BigDecimal.ZERO;
			}
			storeService.updateBalance(groupOrder.getStore(), "订单" + groupOrder.getId(), money.toString(), "1", groupOrder.getId(), groupOrder.getFreight(), groupOrder.getUsername(), groupOrder.getPhone(), new Date());
			
			// 调用三方失效订单
			JSONObject object = apiService.orderInvalid(groupOrder.getId());
			if (!"0000".equals(object.getString("respCode"))) {
				logger.error("我惠会员系统请求失效订单失败：" + object.getString("respMsg"));
			}
			// 处理订单代理
			/*if ("1".equals(groupOrder.getProxyType())) {
				// 调用三方会员系统
				List<WohuiEntity> entityList = Lists.newArrayList();
				entityList.add(new WohuiEntity("POrderNO", groupOrder.getId()));
				JSONObject jsonObject = WohuiUtils.send(WohuiUtils.MSMRefund, entityList);
				if (!"0000".equals(jsonObject.getString("respCode"))) {
					logger.error("三方会员系统订单退款失败：" + jsonObject.getString("respMsg"));
				}
			}*/
		}
	}

	/**
	 * 确认收货
	 * @param groupOrder
	 */
	@Transactional(readOnly = false)
	public void finish(GroupOrder groupOrder) {
		super.save(groupOrder);
		
		// 商家加钱
		// 获取结算价
		//ProductSku productSku = productSkuMapper.get(groupOrder.getSkuId());
		//if (productSku != null) {
		//	BigDecimal amount = new BigDecimal(productSku.getAmount()).multiply(new BigDecimal(groupOrder.getQty()));
			storeService.updateBalance(groupOrder.getStore(), "订单" + groupOrder.getId(), groupOrder.getMoney(), "1", groupOrder.getId(), groupOrder.getFreight(), groupOrder.getUsername(), groupOrder.getPhone(), new Date());
		//}
		// 用户加铜板
		memberService.updatePoint(groupOrder.getMember(), groupOrder.getPoint(), "1");
		
		// 调用三方会员系统
		JSONObject object = apiService.orderSettle(groupOrder.getId(), groupOrder.getAmount(), groupOrder.getPoint());
		if (!"0000".equals(object.getString("respCode"))) {
			logger.error("我惠会员系统请求结算订单失败：" + object.getString("respMsg"));
		}
		// 处理代理申请
		/*if ("1".equals(groupOrder.getProxyType())) {
			// 调用三方接口
			List<WohuiEntity> entityList = Lists.newArrayList();
			entityList.add(new WohuiEntity("POrderNO", groupOrder.getId()));
			JSONObject jsonObject = WohuiUtils.send(WohuiUtils.MSMSureSign, entityList);
			if (!"0000".equals(jsonObject.getString("respCode"))) {
				logger.error("三方会员系统代理确认收货失败：" + jsonObject.getString("respMsg"));
			}
		}*/
		
		// 发消息
		MsgExample example = msgExampleService.getByType("11");
		if (example != null) {
			msgService.insert(groupOrder.getMember(), "系统消息", example.getContent());
		} 
	}

	/**
	 * 取消订单
	 * @param groupOrder
	 */
	@Transactional(readOnly = false)
	public void cancel(GroupOrder groupOrder) {
		super.save(groupOrder);
		
		// 加库存
		mapper.execUpdateSql("UPDATE t_product_sku SET stock = stock + "+groupOrder.getQty()+" WHERE id = '"+groupOrder.getSkuId()+"'");
		// 减销量
		mapper.execUpdateSql("UPDATE t_product SET sales = sales - "+groupOrder.getQty()+" WHERE id = '"+groupOrder.getProduct().getId()+"'");
	}

	/**
	 * 发货
	 * @param groupOrder
	 */
	@Transactional(readOnly = false)
	public void send(GroupOrder groupOrder) {
		super.save(groupOrder);
		
		// 发消息
		MsgExample example = msgExampleService.getByType("10");
		if (example != null) {
			msgService.insert(groupOrder.getMember(), "系统消息", example.getContent());
		}
	}
	
}